package com.ykht.proj.admin.utils;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

/**
 * @author: 何志鹏
 * @date: 2020-04-29 16:10
 */
public class VideoUtil {

	public static File getVideoPic(File video, String picPath) {
		FFmpegFrameGrabber ff = new FFmpegFrameGrabber(video);
		try {
			ff.start();
			int lenght = ff.getLengthInFrames();
			int i = 0;
			Frame f = null;
			while (i < lenght) {
				// 过滤前5帧，避免出现全黑的图片，依自己情况而定
				f = ff.grabFrame();
				if ((i > 5) && (f.image != null)) {
					break;
				}
				i++;
			}

			// 截取的帧图片
			Java2DFrameConverter converter = new Java2DFrameConverter();
			BufferedImage srcImage = converter.getBufferedImage(f);
			int srcImageWidth = srcImage.getWidth();
			int srcImageHeight = srcImage.getHeight();

			// 对截图进行等比例缩放(缩略图)
			int width = 480;
			int height = (int) (((double) width / srcImageWidth) * srcImageHeight);
			BufferedImage thumbnailImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
			thumbnailImage.getGraphics().drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);

			File picFile = new File(picPath);
			ImageIO.write(thumbnailImage, "jpg", picFile);

			ff.stop();
			return picFile;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/*public static void main(String[] args) throws Exception{
		System.out.println(new Date());
//        String videoPath = ResourceUtils.CLASSPATH_URL_PREFIX + "video.mp4";
		URL url = new URL("https://static.quhouse.com/25f6d155a8f149758c7e6e4d9f8fa2b6.mp4");
		URLConnection connection = url.openConnection();
		InputStream inputStream = connection.getInputStream();
		File video = new File("video.mp4");
		OutputStream outputStream = new FileOutputStream(video);
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
			outputStream.write(buffer, 0, bytesRead);
		}
		outputStream.close();
		inputStream.close();
		String picPath = "video.jpg";
		getVideoPic(video, picPath);
		video.delete();
		System.out.println(new Date());
//        System.out.println(videoPath);
	}*/
}